package window;

import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.timestamps.BoundedOutOfOrdernessTimestampExtractor;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;

import java.time.Duration;
import java.util.Locale;

/**
 * keyed 滚动窗口 新版api
 */
public class EventTimeTumblingWindowDemoNew {

    public static void main(String[] args) throws Exception{
        StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(new Configuration());

        DataStreamSource<String> lines = env.socketTextStream("localhost", 8888);



        // watermark
        SingleOutputStreamOperator<String> watermark = lines.assignTimestampsAndWatermarks(
                WatermarkStrategy.<String> forBoundedOutOfOrderness(Duration.ofMillis(0))
                        .withTimestampAssigner(new SerializableTimestampAssigner<String>() {
                            @Override
                            public long extractTimestamp(String s, long l) {
                                return Long.parseLong(s.split(",")[0]);
                            }
                        }));

        SingleOutputStreamOperator<Tuple2<String, Integer>> wordAndCnt = watermark.map(new MapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(String s) throws Exception {
                String[] fields = s.split(",");
                return Tuple2.of(fields[1], Integer.parseInt(fields[2]));
            }
        });


        // keyed and window
        WindowedStream<Tuple2<String, Integer>, String, TimeWindow> window = wordAndCnt.keyBy(t -> t.f0).window(TumblingEventTimeWindows.of(Time.seconds(5)));

        // apply
        SingleOutputStreamOperator<Tuple2<String, Integer>> summed = window.sum(1);

        // sink
        summed.print();

        env.execute("tumbling window");
    }
}
